﻿using System;
using ePipe;
using Letter.Net.Udp;

namespace Letter.Net.Kcp;

abstract class AKcpHost : AHost<KcpTransportOptions, KcpFeatureOptions>
{
    protected AKcpHost(string name) : base(name)
    {
    }
    
    protected IUdpHost host;
    protected Func<IPipe<byte>> channelProvider;
    
    public override void Build()
    {
        var udpTransportOptions = new UdpTransportOptions();
        var udpHostFeatureOptions = new UdpHostFeatureOptions()
        {
            RcvBufferSize = this.featureOptions.RcvBufferSize,
            SndBufferSize = this.featureOptions.SndBufferSize,
            RcvTimeout = this.featureOptions.RcvTimeout,
            SndTimeout = this.featureOptions.SndTimeout,
            Linger = this.featureOptions.Linger
        };
        
        this.host = UdpProvider.Host(this.Name);
        this.host.ConfigureChannelOptions(udpTransportOptions);
        this.host.ConfigureFeatureOptions(udpHostFeatureOptions);
        this.host.ConfigureConnection(this.ConfigureConnection);
        this.host.Build();

        if (this.transportOptions.mode == KcpMode.PACKAGE)
            this.channelProvider = () => { return Pipeline.CreateMultiplePipe(PipeOptions<byte>.Default); };
        else if (this.transportOptions.mode == KcpMode.STREAM)
            this.channelProvider = () => { return Pipeline.CreateStandardPipe(PipeOptions<byte>.Default); };
        else
            throw new Exception("unexpected KcpMode ：" + this.transportOptions.mode);
        base.Build();
    }

    protected abstract AConnection ConfigureConnection();
}